<template>
  <div class="setting-container">
    <div class="app-container">
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"

        @close="closeAssignDialog"
        @open="openAssignDialog"
      >
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          node-key="id"
          :data="permissionList"
          :props="{label:'name'}"
          default-expand-all
          show-checkbox
          check-strictly
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="submitPermission">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="clickShowAdd"
            >新增角色</el-button>
            <!-- 表格 -->
            <!-- :data绑定数组对象 type拿到的下标 -->
            <el-table v-loading="loading" :data="list">
              <el-table-column label="序号" type="index" :index="indexMethod" width="100" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRow(row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />

          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

      </el-card>
    </div>
    <el-dialog title="弹层标题" :visible="showDialog" @close="closeDialog">
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitBtn">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqGetCompanyById, reqAssignPerm } from '@/api/setting'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      treeLoading: false,
      permissionList: [],
      showAssignDialog: false, // 控制弹层的显示隐藏
      roleId: '', // 记录正在操作的角色
      companyForm: {},
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }
        ]
      },
      showDialog: false,
      loading: false,
      page: 1,
      pagesize: 3,
      list: [],
      total: 0
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo() // 获取公司信息
  },
  methods: {
    // 点击确认修改权限
    async submitPermission() {
      await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('成功分配权限')
      this.closeAssignDialog()
    },
    // 打开分配权限弹层
    async openAssignDialog() {
      this.treeLoading = true
      // 1. 显示权限树状结构 (接口已有就是我们权限页面的获取权限接口)
      const { data: data1 } = await reqGetPermissionList()
      // console.log(data, '分配权限数据')
      // 递归封装的显示树状方法
      this.permissionList = tranListToTreeData(data1, '0')
      const { data: data2 } = await reqGetRoleDetail(this.roleId)
      console.log(data2)
      // 调用setCheckedKeys用来数据回显
      this.$refs.tree.setCheckedKeys(data2.permIds)
      this.treeLoading = false
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    clickShowAssignDialog(id) {
      // 记录角色id - 接口要使用，（理解-权限分配给角色，所以后端需要权限们和角色id）
      this.roleId = id
      this.showAssignDialog = true
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    async showEdit(id) {
      const { data } = await reqGetRoleDetail(id)
      this.form = data
      this.showDialog = true
    },
    submitBtn() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          // 编辑操作
          await reqUpdateRole(this.form)
        } else {
          // 添加操作
          await reqAddRole(this.form)
        }
        // 关闭弹框
        this.closeDialog()
        // 重新渲染
        this.getRoleList()
        // 添加成功
        this.$message.success('操作成功')
      })
    },
    closeDialog() {
      this.showDialog = false
      // 重置表单数据
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    clickShowAdd() {
      this.showDialog = true
    },
    delRow(id) {
      this.$confirm('确定删除此角色吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await reqDeleteRole(id)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(() => {

      })
    },
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      // console.log(data)
      this.list = rows
      this.total = total
      this.loading = false
    },
    indexMethod(index) {
      // 举例
      // 一页一条 目前5页
      // 第四页 序号4
      // 第四页前面一共有3页 一页一条，那前面一共多少条 3 * 1
      // 第page页 序号page
      // 第page页 前面有page-1页 一页pagesize条 前面一共多少条 (page-1)*pagesize
      return index + 1 + (this.page - 1) * this.pagesize
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    }
  }
}
</script>

<style>

</style>
